import React, { useEffect, useMemo, useRef } from 'react';
import {
  getTargetElement,
  useIntersectionObserver,
} from '../lazy-load/intersection-observer';
import './header.less';

const classPrefix = `bbt-react-header`;

export type HeaderProps = {
  className?: string;
  styles?: React.CSSProperties;
  /** 用于自定义背景，支持图片，颜色，默认白 */
  showBackground?: string;
  /** 顶部自动占位，默认开启 */
  block?: boolean;
  /** opacity跟随滑动变化，默认开启 */
  scrollOpacity?: boolean;
  children?: React.ReactNode;
  /** 容器样式 */
  containerStyles?: React.CSSProperties;
  /** 滚动容器 */
  root?: Element | undefined | null;
  /** 沉浸式变化程度回调 参数ratio 在0-1之间 */
  onIntersection?: (ratio: number) => void | null | undefined;
};

const Header: React.FC<HeaderProps> = ({
  className = '',
  styles = {},
  showBackground = '#FFFFFF',
  block = true,
  scrollOpacity = true,
  children,
  containerStyles = {},
  root = null,
  onIntersection,
}: HeaderProps) => {
  const headerRef = useRef(null);
  const headerFixRef = useRef<null | HTMLDivElement>(null);
  const [observe, listen] = useIntersectionObserver();

  const opacity = useMemo(() => {
    const rate = scrollOpacity ? observe?.intersectionRatio || 0 : 0;
    let op = 1 - Number(rate);
    op = Math.floor(op * 10) / 10;
    if (op < 0.1) op = 0;
    if (op > 0.9) op = 1;
    const style: React.CSSProperties & Partial<Record<string | never, string>> =
      {
        '--bbt-header-opacity': `${op}`,
        '--bbt-header-background': showBackground,
      };
    onIntersection && onIntersection?.(op);
    return style;
  }, [observe]);

  useEffect(() => {
    listen({
      element: getTargetElement(headerRef.current) as Element,
      threshold: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((el) => el / 10),
      root,
    });
  }, []);

  return (
    <div
      className={`${classPrefix} ${className}`}
      ref={headerRef}
      style={{ ...containerStyles }}
    >
      <div
        className={`${classPrefix}-fix`}
        ref={headerFixRef}
        style={{ ...styles, ...opacity }}
      >
        {children}
      </div>
      {block ? (
        <div
          className={`${classPrefix}-block`}
          style={{
            height: headerFixRef.current?.getBoundingClientRect()?.height || 0,
          }}
        ></div>
      ) : null}
    </div>
  );
};

export { Header };
